package com.example.for_screen;

import android.util.Log;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;

public class SocketLive {
    private SocketCallback socketCallback;
    MyWebSocketClient myWebSocketClient;
    private WebSocket webSocket;
    private int port;

    public SocketLive(SocketCallback socketCallback, int port) {
        this.socketCallback = socketCallback;
        this.port = port;
    }

    public void start(){
        try {
            URI uri = new URI("ws://192.168.1.100:9007");
            myWebSocketClient = new MyWebSocketClient(uri);
            myWebSocketClient.connect();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private class MyWebSocketClient extends WebSocketClient {
        public MyWebSocketClient(URI uri) {
            super(uri);
        }

        @Override
        public void onOpen(ServerHandshake handshakedata) {
            Log.e("111","111");

        }

        @Override
        public void onMessage(String message) {
        }
        @Override
        public void onMessage(ByteBuffer bytes) {
            Log.e("onMessage", bytes.remaining()+"");
            byte[] buf = new byte[bytes.remaining()];
            bytes.get(buf);
            socketCallback.callBack(buf);
        }


        @Override
        public void onClose(int code, String reason, boolean remote) {

        }

        @Override
        public void onError(Exception ex) {
            Log.e("222",ex.toString());
        }
    }
    interface SocketCallback{

        void callBack(byte[] buf);
    }
}
